package org.desktop.web.client.loader;

import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.data.shared.loader.DataProxy;
import com.sencha.gxt.data.shared.writer.DataWriter;

@Deprecated
public class RESTProxy<C> implements DataProxy<C, JavaScriptObject> {

	private String url;
	private DataWriter<C, String> writer;
	
	
	
	public RESTProxy(String url) {
		super();
		this.url = url;
	}



	public void load(C loadConfig, final Callback<JavaScriptObject, Throwable> callback) {
//	    String transId = "transId" + ID++;
//	    String prepend = url.indexOf("?") != -1 ? "&" : "?";
//	    String u = url + prepend + generateUrl(loadConfig);
//		Window.alert(u);

	    JsonpRequestBuilder b = new JsonpRequestBuilder();
//	    b.setPredeterminedId(transId);// needed?
	    b.requestObject(url, new AsyncCallback<JavaScriptObject>() {
	      @Override
	      public void onFailure(Throwable caught) {
	        callback.onFailure(caught);
	      }

	      @Override
	      public void onSuccess(JavaScriptObject result) {
	        callback.onSuccess(result);
	      }
	    });
	  }

	  /**
	   * Sets the proxy's url.
	   * 
	   * @param url the url
	   */
	  public void setUrl(String url) {
	    this.url = url;
	  }

	  /**
	   * Sets the data writer for this proxy. The data writer is responsible for
	   * encoding the load config.
	   * 
	   * @param writer the data writer
	   */
	  public void setWriter(DataWriter<C, String> writer) {
	    this.writer = writer;
	  }

	  /**
	   * Encodes the load config into a format that can be used for a GET query
	   * string or a POST url-encoded body. Use {@link #setWriter} to set the data
	   * writer responsible for encoding the load config. If it is not set the load
	   * config is assumed to require no further encoding and its value is retrieved
	   * using {@link Object#toString()}.
	   * 
	   * @param loadConfig the load config to encode
	   * @return the encoded load config
	   */
	  protected String generateUrl(C loadConfig) {
	    if (writer != null) {
	      return writer.write(loadConfig);
	    } else {
	      if (loadConfig == null) {
	        return "";
	      }
	      return loadConfig.toString();
	    }
	  }
	

}
